// src/hooks/requests.js

const API_URL = 'http://localhost:8000';
// 加载行星数据并返回 JSON 格式
async function httpGetPlanets() {
  const response = await fetch(`${API_URL}/planets`);
  return await response.json();
  }

// 加载发射任务，按任务编号排序后返回 JSON 格式
async function httpGetLaunches() {
  const response = await fetch(`${API_URL}/launches`);
  const fetchedLaunches = await response.json();
  return fetchedLaunches.sort((a, b) => {
  return a.flightNumber - b.flightNumber;
  });
}

// 将提供的发射任务数据提交到发射系统
async function httpSubmitLaunch(launch) {
  try {
    return await fetch(`${API_URL}/launches`, {
    method: "post",
    headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify(launch),
  });
  } catch(err) {
  return {
  ok: false,
  };
  }
}

// 删除指定 ID 的发射任务
async function httpAbortLaunch(id) {
  try {
    return await fetch(`${API_URL}/launches/${id}`, {
        method: "delete",
      });
    } catch(err) {
      console.log(err);
      return {
        ok: false,
      };
    }
  }

// 导出所有请求函数，以便在其他模块中使用
export {
  httpGetPlanets,
  httpGetLaunches,
  httpSubmitLaunch,
  httpAbortLaunch,
};

